package py.com.sole.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import py.com.sole.dao.ArticuloDao;
import py.com.sole.dao.DaoFactory;

import py.com.sole.model.Articulo;

public class ArticuloImpl implements ArticuloDao {

  EntityManager em = DaoFactory.getEm();

  @Override
  public Articulo addArticulo(Articulo articulo) {

    try {
      em.getTransaction().begin();
      em.persist(articulo);
      em.getTransaction().commit();
      return articulo;
    } catch (Exception e) {
      //System.out.println("Error al intentar persistir "+e);
      e.printStackTrace();
      return null;
    }

  }

  @Override
  public void deleteArticulo(int id) {
    try {
      em.getTransaction().begin();
      em.remove(this.getArticuloById(id));
      em.getTransaction().commit();

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  @Override
  public void updateArticulo(Articulo articulo) {
    // TODO Auto-generated method stub
    try {
      em.getTransaction().begin();
      em.merge(this.getArticuloById(articulo.getId()));
      em.getTransaction().commit();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  @SuppressWarnings("all")
  @Override
  public List<Articulo> getArticulos() {
    return em.createQuery("SELECT m FROM Articulo m WHERE m.activo=TRUE").getResultList();
  }

  @Override
  public Articulo getArticuloById(int id) {
    return (Articulo) em.createQuery("SELECT m FROM Articulo m where m.id = " + id).getSingleResult();
  }

  @Override
  public Articulo getArticuloByName(String value) {
    // TODO Auto-generated method stub
    try {
      Query q = em.createNamedQuery("Articulo.findByDescripcion");
      q.setParameter("descripcion", value);
      return (Articulo) q.getSingleResult();
    } catch (Exception e) {
      return null;
    }

  }

}
